# -*- coding: utf-8 -*-
# @Author  : Lison Song
# @Time    : 2023/3/16 20:13

from flask import Blueprint, render_template, request, session, jsonify
from flask_login import login_required, current_user
from sqlalchemy import desc
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import Weixin_articles, Weixin_Official_Acc, Weixin_Official_Acc_log,AdminLog
from applications.models import Robot_Info, Weixin_Official_Acc_Group, Weixin_Official_Acc_Group_ret
from applications.common.appenv import HttpBaseCode
from applications.common.utils.mytools import MyTools

admin_wx_official_acc = Blueprint('admin_wx_official_acc', __name__, url_prefix='/admin/wxOfficialAcc')


# 公众号管理
@admin_wx_official_acc.get('/offaccInfo')
@authorize("admin:wxoffacc:info")
def offaccmain():
    return render_template('admin/weixin/wx_official_acc.html')


#  添加公众号页面
@admin_wx_official_acc.get('/addOffAcc')
@authorize("admin:wxoffacc:add", log=True)
def addOffAcc():
    return render_template('admin/weixin/addOffAcc.html')


#   微信公众号分页查询
@admin_wx_official_acc.get('/offaccData')
@authorize("admin:wxoffacc:info")
def offaccData():
    # 获取请求参数
    wx_name = str_escape(request.args.get('wx_name', type=str))
    filters = []
    if wx_name:
        filters.append(Weixin_Official_Acc.wx_name.contains(wx_name))
    # print(*filters)
    query = db.session.query(
        Weixin_Official_Acc,
        Robot_Info
    ).filter(*filters).outerjoin(Robot_Info, Weixin_Official_Acc.robot_id == Robot_Info.id).order_by(
        Weixin_Official_Acc.update_at.desc()).layui_paginate()

    return table_api(
        data=[{
            'id': offacc.id,
            'wx_name': offacc.wx_name,
            'wx_code': offacc.wx_code,
            'robot_name': Robot_Info.name,
            'avatar': offacc.avatar,
            'enable': offacc.enable,
            'article_nu': offacc.article_nu,
            'update_at': offacc.update_at,
            'create_at': offacc.create_at
        } for offacc, Robot_Info in query.items],
        count=query.total)


# 添加 公众号
@admin_wx_official_acc.post('/offAcc/save')
@authorize("admin:wxoffacc:add", log=True)
def saveOffAcc():
    req_json = request.json
    wx_name = str_escape(req_json.get("wx_name"))
    wx_group_ids = req_json.get('groups')
    robot_id = str_escape(req_json.get('robot_id'))
    print(f"公众号分组数据：{wx_group_ids}")

    if not wx_name or not robot_id:
        return fail_api(msg="公众号名称不得为空")

    if bool(Weixin_Official_Acc.query.filter_by(wx_name=wx_name).count()):
        return fail_api(msg="公众号已经存在")

    weixin_official_acc = Weixin_Official_Acc(wx_name=wx_name, robot_id=robot_id)
    db.session.add(weixin_official_acc)
    db.session.commit()
    res = db.session.query(Weixin_Official_Acc.id).filter(Weixin_Official_Acc.wx_name == wx_name).one()
    wx_id = res[0]
    ## 存入 公众号和 区域分组的关系映射
    if len(wx_group_ids) > 0:
        for groupid in wx_group_ids:
            weixin_Official_Acc_Group_ret = Weixin_Official_Acc_Group_ret(wx_offac_id=wx_id, group_id=groupid)
            db.session.add(weixin_Official_Acc_Group_ret)
            db.session.commit()
    return success_api(msg="增加成功")


# 删除公众号
@admin_wx_official_acc.delete('/offAcc/remove/<int:id>')
@authorize("admin:wxoffacc:remove", log=True)
def offAccDelete(id):
    ##删除关联表数据
    ret = Weixin_Official_Acc_Group_ret.query.filter_by(wx_offac_id=id).delete()
    ret2 = Weixin_articles.query.filter_by(wx_offac_id=id).delete()
    ret3 = Weixin_Official_Acc_log.query.filter_by(wx_id=id).delete()
    db.session.commit()
    ##删除公众号数据
    res = Weixin_Official_Acc.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


#  编辑公众号 返回页面
@admin_wx_official_acc.get('/offAcc/edit/<int:id>')
@authorize("admin:wxoffacc:add", log=True)
def edit(id):
    oa = curd.get_one_by_id(Weixin_Official_Acc, id)
    # oa['groups'] = [1, 2, 3, 4]
    res = db.session.query(Weixin_Official_Acc_Group_ret.group_id).filter(Weixin_Official_Acc_Group_ret.wx_offac_id == id).all()
    print(type(res),res)
    groupids = []
    for item in res:
        groupids.append(item[0])
    print(groupids)
    # print(type(oa))
    wxdata = {}
    wxdata['id'] = oa.id
    wxdata['wx_name'] = oa.wx_name
    wxdata['groups'] = ''.join(str(i) for i in groupids)
    wxdata['robot_id'] = oa.robot_id
    return render_template('admin/weixin/editOffAcc.html', **wxdata)


#   编辑公众号
@admin_wx_official_acc.put('/offAcc/update')
@authorize("admin:wxoffacc:add", log=True)
def offAccupdate():
    req_json = request.json
    id = str_escape(req_json.get("id"))
    wx_name = str_escape(req_json.get('wx_name'))
    wx_group_ids = req_json.get('groups')
    robot_id = str_escape(req_json.get('robot_id'))
    ## 更新公众号表
    Weixin_Official_Acc.query.filter_by(id=id).update(
        {'wx_name': wx_name, 'robot_id': robot_id})

    db.session.commit()
    ##更新关联表
    ret = Weixin_Official_Acc_Group_ret.query.filter_by(wx_offac_id=id).delete()
    db.session.commit()
    if len(wx_group_ids) > 0:
        for groupid in wx_group_ids:
            weixin_Official_Acc_Group_ret = Weixin_Official_Acc_Group_ret(wx_offac_id=id, group_id=groupid)
            db.session.add(weixin_Official_Acc_Group_ret)
            db.session.commit()
    return success_api(msg="更新成功")


# 启用公众号
@admin_wx_official_acc.put('/enable')
@authorize("admin:wxoffacc:add", log=True)
def enable():
    _id = request.json.get('wx_id')
    if _id:
        res = enable_status(model=Weixin_Official_Acc, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用公众号
@admin_wx_official_acc.put('/disable')
@authorize("admin:wxoffacc:add", log=True)
def dis_enable():
    _id = request.json.get('wx_id')
    if _id:
        res = disable_status(model=Weixin_Official_Acc, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


# 公众号文章
@admin_wx_official_acc.get('/articleInfo')
@authorize("admin:wxarticle:info")
def articlemain():
    return render_template('admin/weixin/wx_articles.html')


#   微信公众号文章分页查询
@admin_wx_official_acc.get('/articleData')
@authorize("admin:wxarticle:info")
def articleData():
    # 获取请求参数
    wx_name = str_escape(request.args.get('wx_name', type=str))
    article_title = str_escape(request.args.get('article_title', type=str))
    wx_id = str_escape(request.args.get('wx_id', type=int))
    filters = []
    if wx_id:
        filters.append(Weixin_articles.wx_offac_id == wx_id)
    if wx_name:
        filters.append(Weixin_articles.wx_name.contains(wx_name))
    if article_title:
        filters.append(Weixin_articles.article_title.contains(article_title))
    # print(*filters)
    query = db.session.query(
        Weixin_articles,
        Robot_Info
    ).filter(*filters).outerjoin(Robot_Info, Weixin_articles.robot_id == Robot_Info.id).order_by(
        Weixin_articles.create_at.desc()).layui_paginate()

    return table_api(
        data=[{
            'id': article.id,
            'wx_name': article.wx_name,
            'article_title': article.article_title,
            'article_url': article.article_url,
            'robot_name': Robot_Info.name,
            'create_at': article.create_at
        } for article, Robot_Info in query.items],
        count=query.total)


# 删除公众号文章
@admin_wx_official_acc.delete('/article/remove/<int:id>')
@authorize("admin:wxarticle:remove", log=True)
def wxarticleDelete(id):
    res = Weixin_articles.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


## 获取全部 公众号分组数据 不分页
@admin_wx_official_acc.get('/groupdata')
@login_required
def groupdata():
    result = {}
    try:
        res = db.session.query(Weixin_Official_Acc_Group).order_by(Weixin_Official_Acc_Group.code.asc()).all()
        data = []
        for item in res:
            group = {}
            group['id'] = item.id
            group['name'] = item.name
            group['code'] = item.code
            data.append(group)
        result['data'] = data
        result['count'] = len(res)
        result['code'] = HttpBaseCode.SUCCESS_CODE
        result['message'] = HttpBaseCode.SUCCESS_MESSAGE
    except Exception as e:
        result['code'] = HttpBaseCode.FAIL_CODE
        result['message'] = HttpBaseCode.FAIL_MESSAGE
        print(e)
    return jsonify(result)


# 添加 公众号文章
@admin_wx_official_acc.get('/addArticle')
@authorize("admin:wxarticle:add", log=True)
def addArticle():
    return render_template('admin/weixin/addArticle.html')


# 保存 公众号文章
@admin_wx_official_acc.post('/article/save')
@authorize("admin:wxarticle:add", log=True)
def saveArticle():
    req_json = request.json
    wx_name = str_escape(req_json.get("wx_name"))
    # wx_group_code = str_escape(req_json.get('wx_group_code'))
    article_title = str_escape(req_json.get('article_title'))
    article_url = str_escape(req_json.get('article_url'))
    article_time = str_escape(req_json.get('article_time'))
    article_key = MyTools.getUUID(article_url)

    if not wx_name or not article_title or not article_url:
        return fail_api(msg="公众号名称 标题 URL 不得为空")

    if bool(Weixin_articles.query.filter_by(article_key=article_key).count()):
        return fail_api(msg="文章已经存在")
    oa = Weixin_Official_Acc.query.filter_by(wx_name=wx_name).first()
    if oa:
        wx_offac_id = oa.id
    else:
        return fail_api(msg="公众号部存在，请先添加公众号")
    # robotid = 0 为人工采集
    article = Weixin_articles(wx_name=wx_name, article_title=article_title, article_url=article_url,
                              article_time=article_time, wx_offac_id=wx_offac_id, article_key=article_key, robot_id=0)
    db.session.add(article)
    db.session.commit()
    return success_api(msg="增加成功")


#  获取任务公众号信息
@admin_wx_official_acc.get('/getOffAcc')
@login_required
def getOffAcc():
    result = {}
    try:
        res = db.session.query(Weixin_Official_Acc).order_by(Weixin_Official_Acc.wx_group_code.asc()).all()
        data = []
        for item in res:
            oa = {}
            oa['id'] = item.id
            oa['wx_name'] = item.wx_name
            oa['wx_group_code'] = item.wx_group_code
            oa['enbale'] = item.enable
            oa['create_at'] = item.create_at
            data.append(oa)
        result['data'] = data
        result['count'] = len(res)
        result['code'] = HttpBaseCode.SUCCESS_CODE
        result['message'] = HttpBaseCode.SUCCESS_MESSAGE
    except Exception as e:
        result['code'] = HttpBaseCode.FAIL_CODE
        result['message'] = HttpBaseCode.FAIL_MESSAGE
        print(e)
    return jsonify(result)
